package com.xiaoma.myaudience.biz.activity;

import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.model.NeteasePostFeedBackInfo;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.PostFeedBackTask;
import com.xiaoma.myaudience.biz.util.VideoPrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;

/**
 * 用户意见反馈页面.
 * 
 * @author ddtou
 */
public class FeedBackActivity extends BaseActivity {
	
	private Context mContext;
	private PostFeedBackTask mPostFeedbackTask;
	
	private String mHeadinfo;
	private String mMessage;
	private String mEmail;
	
	private TextView mFeedbackTextCount;
	private EditText mEditFeedbackMessage;
	private EditText mFeedbackEmail;
	private Button mSubmitFeedback;
	
	private ProgressDialog proDialog;
	
	private InputMethodManager mIputMethodManager;
	
	private final String FEEDBACK_EMAIL = "feedback_email";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	setContentView(R.layout.personal_feedback);
    	
    	setNetEaseTitleBarVisibility(View.VISIBLE);
    	setNetEaseTitle(R.string.title_feedback);
    	setNetEaseTitleGravity(Gravity.CENTER_VERTICAL);
    	
        mContext = this;
        
        mHeadinfo = String.format("%s%s%s%s%s%s%s", "[android_", getResources().getString(R.string.version_build_no),
        		"_", Build.MODEL, "_", Build.VERSION.RELEASE, "]");
        
        findView();
        setlayoutClickListener();
        
        initEmail2EditText();

		mEditFeedbackMessage.requestFocus();
        if(null != mIputMethodManager)
        	mIputMethodManager.showSoftInput(mEditFeedbackMessage, 0);
    }


	/**初始化组件*/
	private void findView() {
		// TODO Auto-generated method stub
		mIputMethodManager = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);

		mFeedbackTextCount = (TextView)findViewById(R.id.text_remain_str_count);;
		mEditFeedbackMessage = (EditText)findViewById(R.id.edit_feedbackmessage);
		mFeedbackEmail = (EditText)findViewById(R.id.edit_feedback_email);;
		mSubmitFeedback = (Button)findViewById(R.id.btn_submit_feedback);;
		
		mFeedbackTextCount.setText(Html.fromHtml(String.format(
				"%s%s%s", getResources().getString(R.string.str_input_tips_front), 
				"<font color=\"#e80f0f\">500</font>", getResources().getString(R.string.str_input_tips_tail))));

		proDialog = new ProgressDialog(mContext);
		proDialog.setMessage(getResources().getString(R.string.str_post_message_ing));
		proDialog.setCancelable(true);
		
		proDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				cancelPostFeedbackTask();
			}
		});
		
	}
    
    /**设置组件监听动作*/
	private void setlayoutClickListener() {
		// TODO Auto-generated method stub
		mSubmitFeedback.setOnClickListener(feedbackListener);
		
		mEditFeedbackMessage.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;				
			private int length = 0;
			
			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				temp = arg0;
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				
				length = 500-temp.length();
				mFeedbackTextCount.setText(Html.fromHtml(String.format(
						"%s%s%d%s%s", getResources().getString(R.string.str_input_tips_front), 
						"<font color=\"#e80f0f\">", length, "</font>", getResources().getString(R.string.str_input_tips_tail))));
				
			}
			
		});
	}
	
	/**
	 * 设置用户反馈邮箱
	 * 如果有反馈邮箱，则将反馈邮箱设置到邮箱中
	 * 否则将当前登陆的账号设置到反馈邮箱中
	 */
	private void initEmail2EditText(){
		String email = VideoPrefHelper.getString(mContext, FEEDBACK_EMAIL, "");
		if(null == email || "".equals(email)){
			AudienceApplication app = (AudienceApplication)getApplication();
			if(app.isLogin()){
				email = app.getUserAccount();
			}
		}
		mFeedbackEmail.setText(email);
	}
	
	/** 提交Button Listener */
	private OnClickListener feedbackListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//do_feedback_button.setEnabled(false);
			
			String message = String.format("%s", mEditFeedbackMessage.getText());
			String email = String.format("%s", mFeedbackEmail.getText());
			
			if(null != message && !"".equals(message.trim()) &&message.trim().length()>4){
				
				if(message.trim().length()>500){
					Tips(getResources().getString(R.string.str_input_feedback_length));
				}else{
					
					mMessage = message.trim();
					mEmail = email;
					
					VideoPrefHelper.putString(mContext, FEEDBACK_EMAIL, email);
					startPostFeedbackTask();
				}
			}else{
				Tips(getResources().getString(R.string.str_input_feedback_text));
			}
			
		}
	};
	
	/**启动提交任务*/
	private void startPostFeedbackTask() {
		cancelPostFeedbackTask();
		mPostFeedbackTask = new PostFeedBackTask(mContext,
				DataAsyncTask.TASK_POST_FEEDBACK, this);
		
		String title = String.format("%s%s", mHeadinfo, mMessage.substring(0, mMessage.length()>10?10:mMessage.length()));
		title = title.substring(0, title.length()>35?35:title.length());
		String message = mMessage;
		String email = mEmail;
		
		NeteasePostFeedBackInfo feedbackInfo = new NeteasePostFeedBackInfo();
		feedbackInfo.mTitle = title;
		feedbackInfo.mMessage = message;
		feedbackInfo.mEmail = email;
		
		mPostFeedbackTask.execute(feedbackInfo);
	}

	/**关闭提交任务*/
	private void cancelPostFeedbackTask() {
		if (mPostFeedbackTask != null) {
			mPostFeedbackTask.cancel(true, true);
		}
		mPostFeedbackTask = null;
	}
	

	/**
	 * 开始提交
	 */
	@Override
	public void onPreExecute(int what) {
		// TODO Auto-generated method stub
		super.onPreExecute(what);
		
		proDialog.show();
	}
	
	/**
	 * 提交完成
	 */
	@Override
	public void onPostExecute(int what, Object o) {
		// TODO Auto-generated method stub
		super.onPostExecute(what, o);
		proDialog.dismiss();
		if (o == null) {
			Tips(getResources().getString(R.string.str_post_feedback_fail));
			return;
		}
		
		switch (what) {
		case DataAsyncTask.TASK_POST_FEEDBACK:
			
			Map<String,Object> result = (Map<String,Object>)o;
			String code = (String) result.get("code");
			if(!code.equals("0")){
				Tips(getResources().getString(R.string.str_post_feedback_fail));
			} else {
				Tips(getResources().getString(R.string.str_post_feedback_success));
				finish();
			}
			
			break;

		default:
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		cancelPostFeedbackTask();
	}
	
}
